use axum::{extract::{DefaultBodyLimit, Query}, routing::{get, post}, Router};
use serde::Deserialize;

use crate::{error::AppErr, server::{req::handler::adv_notify_all, res::{new_download, DownloadFile, Void}, Cbor}, store::adv::{self, TbAdv}};

#[derive(Debug, Deserialize)]
struct CreateReq {
    adv_type: u8,
    name: String,
    #[serde(with = "serde_bytes")]
    body: Box<[u8]>,
}

async fn on_create(req: Cbor<CreateReq>) -> Result<Cbor<u64>, AppErr> {
    let id = adv::create(req.adv_type, &req.name, &req.body).await?;
    adv_notify_all();
    Ok(Cbor(id))
}


async fn on_query() -> Result<Cbor<Box<[TbAdv]>>, AppErr> {
    let res = adv::query_all().await?;
    Ok(Cbor(res))
}

#[derive(Debug, Deserialize)]
struct DeleteReq {
    id: u64,
}

async fn on_delete(req: Cbor<DeleteReq>) -> Result<Void, AppErr> {
    adv::delete(req.id).await?;
    adv_notify_all();
    Ok(Void)
}

async fn on_download(req: Query<DeleteReq>) -> Result<DownloadFile, AppErr> {
    let ret = adv::download(req.id).await?;
    Ok(new_download(ret.name, ret.body))
}

const MAX_ADV_SIZE: usize = 120 * 1024 * 1024;

pub fn register() -> Router {
    Router::new()
        .route("/create", post(on_create))
        .layer(DefaultBodyLimit::max(MAX_ADV_SIZE))
        .route("/query_all", get(on_query))
        .route("/delete", post(on_delete))
        .route("/download", get(on_download))

}
